import { View, Text, StyleSheet, TextInput, TouchableOpacity, ActivityIndicator, ScrollView, Image, Alert, FlatList } from 'react-native';
import React, { useState, useEffect } from 'react';
import { Stack, useRouter } from 'expo-router';
import { useTheme } from '../context/ThemeContext';
import { createGroup, getFriendList, FriendType } from '../services/chatService';
import { MaterialCommunityIcons } from '@expo/vector-icons';

export default function CreateGroupScreen() {
  const { isDarkMode } = useTheme();
  const router = useRouter();
  
  const [groupName, setGroupName] = useState('');
  const [description, setDescription] = useState('');
  const [loading, setLoading] = useState(false);
  const [creating, setCreating] = useState(false);
  const [friends, setFriends] = useState<FriendType[]>([]);
  const [selectedFriends, setSelectedFriends] = useState<number[]>([]);
  
  // 加载好友列表
  useEffect(() => {
    const loadFriends = async () => {
      try {
        setLoading(true);
        
        // 使用模拟数据
        const mockFriends: FriendType[] = [
          {
            friendId: 2,
            remark: '李同学',
            userName: '李四',
            userAvatar: 'https://randomuser.me/api/portraits/men/2.jpg',
            userProfile: '软件工程专业学生',
            createTime: '2023-01-01 12:00:00'
          },
          {
            friendId: 3,
            remark: '王同学',
            userName: '王五',
            userAvatar: 'https://randomuser.me/api/portraits/men/3.jpg',
            userProfile: '计算机科学专业学生',
            createTime: '2023-01-02 12:00:00'
          },
          {
            friendId: 4,
            remark: '赵老师',
            userName: '赵六',
            userAvatar: 'https://randomuser.me/api/portraits/men/4.jpg',
            userProfile: '计算机科学教授',
            createTime: '2023-01-03 12:00:00'
          }
        ];
        
        // 在实际应用中，这里应该调用API
        // const friendsList = await getFriendList();
        setFriends(mockFriends);
      } catch (error) {
        console.error('加载好友列表失败:', error);
        Alert.alert('错误', '加载好友列表失败，请重试');
      } finally {
        setLoading(false);
      }
    };
    
    loadFriends();
  }, []);
  
  // 选择或取消选择好友
  const toggleFriendSelection = (friendId: number) => {
    if (selectedFriends.includes(friendId)) {
      setSelectedFriends(selectedFriends.filter(id => id !== friendId));
    } else {
      setSelectedFriends([...selectedFriends, friendId]);
    }
  };
  
  // 创建群组
  const handleCreateGroup = async () => {
    if (!groupName.trim()) {
      Alert.alert('提示', '请输入群组名称');
      return;
    }
    
    if (selectedFriends.length === 0) {
      Alert.alert('提示', '请至少选择一个好友');
      return;
    }
    
    try {
      setCreating(true);
      
      // 在实际应用中，这里应该调用API
      // const groupId = await createGroup(groupName.trim(), '', description.trim(), selectedFriends);
      
      // 模拟创建群组
      setTimeout(() => {
        const mockGroupId = 101;
        setCreating(false);
        Alert.alert('成功', '群组创建成功', [
          {
            text: '确定',
            onPress: () => router.push(`/chat/group/${mockGroupId}?name=${encodeURIComponent(groupName.trim())}`)
          }
        ]);
      }, 1000);
      
    } catch (error) {
      console.error('创建群组失败:', error);
      Alert.alert('错误', '创建群组失败，请重试');
      setCreating(false);
    }
  };
  
  // 渲染好友项
  const renderFriendItem = ({ item }: { item: FriendType }) => {
    const isSelected = selectedFriends.includes(item.friendId);
    
    return (
      <TouchableOpacity
        style={[
          styles.friendItem,
          { 
            backgroundColor: isDarkMode ? '#1A1A1A' : '#FFFFFF',
            borderColor: isDarkMode ? '#333333' : '#EEEEEE'
          }
        ]}
        onPress={() => toggleFriendSelection(item.friendId)}
      >
        <Image 
          source={{ uri: item.userAvatar }} 
          style={styles.avatar}
        />
        
        <View style={styles.friendInfo}>
          <Text style={[
            styles.friendName,
            { color: isDarkMode ? '#FFFFFF' : '#000000' }
          ]}>
            {item.remark || item.userName}
          </Text>
          
          <Text style={[
            styles.friendProfile,
            { color: isDarkMode ? '#BBBBBB' : '#666666' }
          ]}>
            {item.userProfile || '暂无个人介绍'}
          </Text>
        </View>
        
        <MaterialCommunityIcons 
          name={isSelected ? "checkbox-marked-circle" : "checkbox-blank-circle-outline"} 
          size={24} 
          color={isSelected ? (isDarkMode ? '#3B82F6' : '#2563EB') : (isDarkMode ? '#666666' : '#CCCCCC')} 
        />
      </TouchableOpacity>
    );
  };
  
  return (
    <>
      <Stack.Screen options={{ 
        title: '创建群聊',
        headerStyle: {
          backgroundColor: isDarkMode ? '#1E1E1E' : '#FFFFFF',
        },
        headerTintColor: isDarkMode ? '#FFFFFF' : '#333333',
      }} />
      
      <View 
        style={[
          styles.container,
          { backgroundColor: isDarkMode ? '#121212' : '#F5F5F5' }
        ]}
      >
        {/* 群组信息输入 */}
        <View style={[
          styles.groupInfoSection,
          { 
            backgroundColor: isDarkMode ? '#1A1A1A' : '#FFFFFF',
            borderColor: isDarkMode ? '#333333' : '#EEEEEE'
          }
        ]}>
          <View style={styles.inputRow}>
            <Text style={[
              styles.label,
              { color: isDarkMode ? '#FFFFFF' : '#000000' }
            ]}>
              群组名称:
            </Text>
            
            <TextInput
              style={[
                styles.input,
                { 
                  backgroundColor: isDarkMode ? '#2A2A2A' : '#F5F5F5',
                  color: isDarkMode ? '#FFFFFF' : '#000000'
                }
              ]}
              placeholder="请输入群组名称（必填）"
              placeholderTextColor={isDarkMode ? '#999999' : '#999999'}
              value={groupName}
              onChangeText={setGroupName}
              maxLength={20}
            />
          </View>
          
          <View style={styles.inputRow}>
            <Text style={[
              styles.label,
              { color: isDarkMode ? '#FFFFFF' : '#000000' }
            ]}>
              群组描述:
            </Text>
            
            <TextInput
              style={[
                styles.textArea,
                { 
                  backgroundColor: isDarkMode ? '#2A2A2A' : '#F5F5F5',
                  color: isDarkMode ? '#FFFFFF' : '#000000'
                }
              ]}
              placeholder="请输入群组描述（选填）"
              placeholderTextColor={isDarkMode ? '#999999' : '#999999'}
              value={description}
              onChangeText={setDescription}
              multiline
              numberOfLines={3}
              maxLength={100}
              textAlignVertical="top"
            />
          </View>
        </View>
        
        {/* 好友选择列表 */}
        <View style={styles.friendsSection}>
          <View style={styles.sectionHeader}>
            <Text style={[
              styles.sectionTitle,
              { color: isDarkMode ? '#FFFFFF' : '#000000' }
            ]}>
              选择好友
            </Text>
            
            <Text style={[
              styles.selectedCount,
              { color: isDarkMode ? '#3B82F6' : '#2563EB' }
            ]}>
              已选择: {selectedFriends.length}
            </Text>
          </View>
          
          {loading ? (
            <View style={styles.loadingContainer}>
              <ActivityIndicator size="large" color={isDarkMode ? '#3B82F6' : '#2563EB'} />
              <Text style={{ color: isDarkMode ? '#BBBBBB' : '#666666', marginTop: 10 }}>
                加载好友中...
              </Text>
            </View>
          ) : (
            <FlatList
              data={friends}
              renderItem={renderFriendItem}
              keyExtractor={item => item.friendId.toString()}
              contentContainerStyle={styles.friendsList}
              ListEmptyComponent={
                <View style={styles.emptyContainer}>
                  <Text style={{ color: isDarkMode ? '#BBBBBB' : '#999999' }}>
                    暂无好友
                  </Text>
                </View>
              }
            />
          )}
        </View>
        
        {/* 创建按钮 */}
        <View style={styles.createButtonContainer}>
          <TouchableOpacity
            style={[
              styles.createButton,
              { 
                backgroundColor: groupName.trim() && selectedFriends.length > 0 ?
                  (isDarkMode ? '#3B82F6' : '#2563EB') :
                  (isDarkMode ? '#666666' : '#CCCCCC')
              }
            ]}
            onPress={handleCreateGroup}
            disabled={creating || !groupName.trim() || selectedFriends.length === 0}
          >
            {creating ? (
              <ActivityIndicator size="small" color="#FFFFFF" />
            ) : (
              <Text style={styles.createButtonText}>创建群组</Text>
            )}
          </TouchableOpacity>
        </View>
      </View>
    </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
  },
  groupInfoSection: {
    borderRadius: 8,
    padding: 16,
    marginBottom: 16,
    borderWidth: 1,
  },
  inputRow: {
    marginBottom: 16,
  },
  label: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 8,
  },
  input: {
    height: 40,
    borderRadius: 8,
    paddingHorizontal: 10,
  },
  textArea: {
    borderRadius: 8,
    paddingHorizontal: 10,
    paddingVertical: 10,
    minHeight: 80,
  },
  friendsSection: {
    flex: 1,
    marginBottom: 16,
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
  },
  sectionTitle: {
    fontSize: 16,
    fontWeight: 'bold',
  },
  selectedCount: {
    fontSize: 14,
    fontWeight: 'bold',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  friendsList: {
    paddingBottom: 16,
  },
  friendItem: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 12,
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 8,
  },
  avatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
  },
  friendInfo: {
    flex: 1,
    marginHorizontal: 12,
  },
  friendName: {
    fontSize: 16,
    fontWeight: 'bold',
    marginBottom: 4,
  },
  friendProfile: {
    fontSize: 14,
  },
  emptyContainer: {
    padding: 20,
    alignItems: 'center',
  },
  createButtonContainer: {
    paddingVertical: 16,
  },
  createButton: {
    height: 50,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  createButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: 'bold',
  }
}); 